"""
模板数据 Schema
用于模板数据的序列化和验证
"""
from datetime import datetime
from typing import Optional, Dict, Any
from pydantic import BaseModel, Field, ConfigDict


class TemplateDataBase(BaseModel):
    """模板数据基础 Schema"""
    template_id: int = Field(..., description="模板表ID")
    template_version: int = Field(..., description="模板版本号")
    patient_id: int = Field(..., description="患者ID")
    doctor_id: int = Field(..., description="医生ID")
    medical_record_id: Optional[int] = Field(None, description="病历ID（可选）")
    form_data: Dict[str, Any] = Field(..., description="表单填写数据")


class TemplateDataCreate(BaseModel):
    """创建模板数据 Schema"""
    template_id: int = Field(..., description="模板表ID")
    template_version: int = Field(..., description="模板版本号")
    patient_id: int = Field(..., description="患者ID")
    doctor_id: Optional[int] = Field(None, description="医生ID（可选，不传则从患者表获取）")
    medical_record_id: Optional[int] = Field(None, description="病历ID（可选）")
    form_data: Dict[str, Any] = Field(..., description="表单填写数据")
    status: Optional[int] = Field(1, description="状态 1-已完成 0-待完成，默认为1")


class TemplateDataUpdate(BaseModel):
    """更新模板数据 Schema"""
    form_data: Optional[Dict[str, Any]] = Field(None, description="表单填写数据")
    status: Optional[int] = Field(None, description="状态 1-启用 0-禁用")


class TemplateDataInDB(TemplateDataBase):
    """数据库中的模板数据 Schema"""
    id: int
    template_name: Optional[str] = None
    patient_name: Optional[str] = None
    status: int
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class TemplateDataResponse(TemplateDataInDB):
    """返回给前端的模板数据 Schema"""
    
    def to_flask_format(self) -> dict:
        """转换为 Flask 风格的响应格式"""
        return {
            "id": self.id,
            "template_id": self.template_id,
            "template_name": self.template_name,
            "template_version": self.template_version,
            "patient_id": self.patient_id,
            "patient_name": self.patient_name,
            "doctor_id": self.doctor_id,
            "medical_record_id": self.medical_record_id,
            "form_data": self.form_data,
            "status": self.status,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }

class TemplateDataWithDetailResponse(TemplateDataResponse):
    """包含模板详情的模板数据响应"""
    template_detail: Optional[Dict[str, Any]] = Field(None, description="模板详情（结构定义）")

    def to_flask_format_with_detail(self) -> dict:
        """转换为 Flask 风格的响应格式（包含模板详情）"""
        data = self.to_flask_format()
        data["template_detail"] = self.template_detail
        return data
